import { useState, useEffect, useMemo } from 'react'

import { TodoHeader, TodoContent, TodoFooter } from './todos/index'

import type { TodoItem } from './todos'

import { deleteAsyncTodo, getAsyncTodoList, updateAsyncTodo, addAsyncTodo } from './api'

function App() {
  const [todoList, updateList] = useState<TodoItem[]>([])

  const [active, setActive] = useState('')

  const addTodo = (content: string) => {
    const obj: TodoItem = {
      id: Date.now(),
      content,
      done: false
    }
    addAsyncTodo(obj)
    updateList([obj, ...todoList])
  }

  const checkActive = (active: string) => {
    setActive(active)
  }

  const listTodo = useMemo(() => {
    switch (active) {
      case 'Active':
        return todoList.filter((item) => !item.done)
      case 'Completed':
        return todoList.filter((item) => item.done)
      default:
        return todoList
    }
  }, [active, todoList])

  const onClear = () => {
    updateList(todoList.filter((item) => !item.done))
  }

  const getTodoList = async () => {
    try {
      const res: any = await getAsyncTodoList()
      if (!res) return
      updateList(res)
      checkActive('All')
    } catch (error) {}
  }

  useEffect(() => {
    getTodoList()
  }, [])

  function updateTodoItem(id: number, content: string) {
    updateAsyncTodo(id, { content })
    todoList.forEach((v) => {
      if (v.id === id) {
        v.content = content
      }
    })
    updateList(todoList)
  }

  function changeCheckbox(id: number) {
    const obj = todoList.find((item) => item.id === id)
    updateAsyncTodo(id, { done: !obj?.done })
    updateList(
      todoList.map((v) => {
        if (v.id === id) {
          v.done = !v.done
        }
        return v
      })
    )
  }

  function removeTodo(id: number) {
    deleteAsyncTodo(id)
    updateList(todoList.filter((v) => v.id !== id))
  }

  return (
    <section className="todoapp">
      <TodoHeader addTodo={addTodo} />
      <TodoContent
        todoList={listTodo}
        changeCheckbox={changeCheckbox}
        removeTodo={removeTodo}
        updateTodoItem={updateTodoItem}
      />
      <TodoFooter checkActive={checkActive} onClear={() => onClear()} />
    </section>
  )
}

export default App
